//
//  Navigator.swift
//  SwiftSign
//
//  Created by continue on 2021/4/23.
//

import UIKit


protocol Navigatable {
    var navigator: Navigator! { get set }
    
}

class Navigator {
    static var `default` = Navigator()
    
    enum Scene {
        case home(viewModel: ViewModel)
        case loginMenu(viewModel: ViewModel)
        case phoneLogin(viewModel: ViewModel)
    }
    
    enum Transition {
        case root(in: UIWindow)
        case navigation
        case modal
    }
    
    func get(segue: Scene) -> UIViewController? {
        switch segue {
        case .home(let viewModel):
            let homeVC = HomeViewController(viewModel: viewModel, navigator: self)
            let nav = NavigationController(rootViewController: homeVC)
            return nav
        case .loginMenu(let viewModel): return LoginMenuViewController(viewModel: viewModel, navigator: self)
        case .phoneLogin(let viewModel): return PhoneLoginViewController(viewModel: viewModel, navigator: self)
        }

    }
    
    func show(segue: Scene, sender: UIViewController?, transition: Transition = .navigation) {
        if let target = get(segue: segue) {
            show(target: target, sender: sender, transition: transition)
        }
    }
    
    
    private func show(target: UIViewController, sender: UIViewController?, transition: Transition) {
        switch transition {
        case .root(in: let window):
            window.rootViewController = target
            return
        default: break
        }
        

        guard let sender = sender else {
            fatalError("You need to pass in a sender for .navigation or .modal transitions")
        }
        
        switch transition {
        case .navigation:
            if let nav = sender.navigationController {
                // push controller to navigation stack
                nav.pushViewController(target, animated: true)
            }
        case .modal:
            // present modally
            DispatchQueue.main.async {
                let nav = NavigationController(rootViewController: target)
                sender.present(nav, animated: true, completion: nil)
            }
        default: break
        }
    }
}
